import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../models/role.entity';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
  ) {}

  findAll(): Promise<Role[]> {
    return this.roleRepository.find();
  }

  findOne(id: number): Promise<Role | null> {
    return this.roleRepository.findOneBy({ id });
  }

  create(roleData: Partial<Role>): Promise<Role> {
    const role = this.roleRepository.create(roleData);
    return this.roleRepository.save(role);
  }

  async update(id: number, roleData: Partial<Role>): Promise<Role | null> {
    const role = await this.findOne(id);
    if (!role) {
      return null;
    }
    this.roleRepository.merge(role, roleData);
    return this.roleRepository.save(role);
  }

  async remove(id: number): Promise<Role | null> {
    const role = await this.findOne(id);
    if (!role) {
      return null;
    }
    return this.roleRepository.remove(role);
  }
}
